<template>
  <div>
    <!-- 面包屑导航 -->
    <el-breadcrumb separator="/">
        <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
        <el-breadcrumb-item>权限管理</el-breadcrumb-item>
        <el-breadcrumb-item>角色列表</el-breadcrumb-item>
    </el-breadcrumb>

    <el-card>
        <el-row>
            <el-col><el-button type="primary">添加角色</el-button></el-col>
        </el-row>
        <el-table :data="rolesList" border stripe>
            <el-table-column type="expand">
                <template v-slot="scope">
                    <el-row :class="['bdbottom',index === 0 ?'bdtop':'','vcenter']" v-for="(item,index) in scope.row.children" :key="item.id">
                        <!-- 渲染一级权限 -->
                        {{i1}}
                        <el-col :span="5">
                            <el-tag closable @close="deleteRightByID(scope.row,item.id)">{{item.authName}}</el-tag>
                            <i class="el-icon-arrow-right"></i>
                        </el-col>
                        <!-- 渲染二、三级权限 -->
                        <el-col :span="19">
                            <!-- 通过for循环嵌套二级权限 -->
                            <el-row :class="[index2 === 0 ?'':'bdtop','vcenter']" v-for="(item2,index2) in item.children" :key="item2.id">
                                <el-col :span="6">
                                    <el-tag type="success" closable @close="deleteRightByID(scope.row,item2.id)">{{item2.authName}}</el-tag>
                                    <i class="el-icon-arrow-right"></i>
                                </el-col>
                                <el-col :span="18">
                                    <el-tag v-for="item3 in item2.children" :key="item3.id" type="warning" closable @close="deleteRightByID(scope.row,item3.id)">{{item3.authName}}</el-tag>
                                </el-col>
                            </el-row>
                        </el-col>
                    </el-row>
                </template>
            </el-table-column>
            <el-table-column type="index"></el-table-column>
            <el-table-column label="角色名称" prop="roleName"></el-table-column>
            <el-table-column label="角色描述" prop="roleDesc"></el-table-column>
            <el-table-column label="操作" width="300px">
                <template v-slot="scope">
                    <el-button size="mini" type="primary" icon="el-icon-search">编辑</el-button>
                    <el-button size="mini" type="danger" icon="el-icon-delete">删除</el-button>
                    <el-button size="mini" type="warning" icon="el-icon-setting" @click="showSetRightDialog(scope.row)">分配权限</el-button>
                </template>
            </el-table-column>
        </el-table>
    </el-card>
    <el-dialog title="分配权限" :visible.sync="setRightDialogVisible" width="50%" @close="setRightDialogClose">
        <el-tree 
            :data="rightsList" 
            :props="treeProps" 
            show-checkbox 
            node-key="id" 
            default-expand-all 
            :default-checked-keys="defKeys"
            ref="treeRef"
        ></el-tree>
        <span slot="footer" class="dialog-footer">
            <el-button @click="setRightDialogVisible = false">取 消</el-button>
            <el-button type="primary" @click="allotRights">确 定</el-button>
        </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
    name:'Roles',
    data(){
        return {
            rolesList:[],
            setRightDialogVisible:false,
            rightsList:[],
            treeProps:{
                children: 'children',
                label: 'authName'
            },
            defKeys:[],
            roleID:''
        }
    },
    created(){
        this.getRolesList()
    },
    methods:{
        async getRolesList(){
            const {data:res} = await this.$http.get('roles')
            if (res.meta.status !== 200) {
                return this.$message.error('角色列表获取失败')
            }
            this.rolesList = res.data
        },
        async deleteRightByID(role,rightID){
            const confirmRes  = await this.$confirm('确认要删除该权限吗？', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).catch(err => err)
            if (confirmRes !== 'confirm') {
                return 
            }
            const {data:res} = await this.$http.delete(`roles/${role.id}/rights/${rightID}`)
            if (res.meta.status !== 200) {
                return this.$message.error('权限删除失败')
            }
            // this.getRolesList()
            // 防止删除后，展开的区块合并
            role.children = res.data
            this.$message.success('权限删除成功')
        },
        async showSetRightDialog(role){
            const {data:res} = await this.$http.get('rights/tree')
            if (res.meta.status !== 200) {
                return this.$message.error('权限获取失败')
            }
            this.rightsList = res.data
            this.getLeafKeys(role,this.defKeys)
            this.setRightDialogVisible = true,
            this.roleID = role.id
        },
        // 通过递归的形式，获取角色下所有三级权限的ID，并保存到defKeys数组中
        getLeafKeys(node,arr){
            if (!node.children) {
                return arr.push(node.id)
            }
            node.children.forEach(item => {
                this.getLeafKeys(item,arr)
            });
        },
        setRightDialogClose(){
            this.defKeys=[]
        },
        async allotRights(){
            const keys = [
                ...this.$refs.treeRef.getCheckedKeys(),
                ...this.$refs.treeRef.getHalfCheckedKeys()
            ]
            const keysStr = keys.join(',')
            const {data:res} = await this.$http.post(`roles/${this.roleID}/rights`,{rids:keysStr})
            if (res.meta.status !== 200) {
                return this.$message.error('分配权限失败')
            }
            this.$message.success('分配权限成功')
            this.getRolesList()
            this.setRightDialogVisible = false
        }
    }
}
</script>

<style lang="less" scoped>
.el-tag{
    margin:7px;
}
.bdtop{
    border-top:1px solid #eee;
}
.bdbottom{
    border-bottom:1px solid #eee
}
.vcenter{
    display: flex;
    align-items:center;
}
</style>